import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login',
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue'),
    },
    {
      path: '/',
      component: () => import('../views/Layout.vue'),
      children: [
        {
          path: '/home',
          name: 'home',
          component: () => import('../views/Home.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: '/basic-query',
          name: 'basic-query',
          component: () => import('../views/BasicQuery.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: '/buffer-analysis',
          name: 'buffer-analysis',
          component: () => import('../views/BufferAnalysis.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: '/station-management',
          name: 'station-management',
          component: () => import('../views/admin/StationManagement.vue'),
          meta: { requiresAuth: true, requiresAdmin: true },
        },
        {
          path: '/line-management',
          name: 'line-management',
          component: () => import('../views/admin/LineManagement.vue'),
          meta: { requiresAuth: true, requiresAdmin: true },
        },
        {
          path: '/statistics',
          name: 'statistics',
          component: () => import('../views/admin/Statistics.vue'),
          meta: { requiresAuth: true, requiresAdmin: true },
        },
        {
          path: '/analysis',
          name: 'analysis',
          component: () => import('../views/admin/Analysis.vue'),
          meta: { requiresAuth: true, requiresAdmin: true },
        },
        {
          path: '/passenger-flow-analysis',
          name: 'passenger-flow-analysis',
          component: () => import('../views/admin/PassengerFlowAnalysis.vue'),
          meta: { requiresAuth: true, requiresAdmin: true },
        },
      ],
    },
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const isLoggedIn = userStore.isLoggedIn
  const userRole = userStore.userInfo?.role

  // 需要登录的页面
  if (to.meta.requiresAuth && !isLoggedIn) {
    next('/login')
    return
  }

  // 需要管理员权限的页面
  if (to.meta.requiresAdmin && userRole !== 'admin') {
    next('/home')
    return
  }

  // 已登录用户访问登录页面，重定向到首页
  if (to.path === '/login' && isLoggedIn) {
    next('/home')
    return
  }

  next()
})

export default router
